# -*- coding: utf-8 -*-

from analysis.games.es import emit_game_order
from common import orm
from common.cache import ProxyAgent
from common.platform.common.model import PLATFORM_TYPE
from common.platform.metis.model import MetisBetLogs
# from common.platform.hera.model import HeraBetLogs
from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)

BATCH_COUNT = 500
DELAY_MINUTES = 5


# Metis
def sync_bet_metis():
    def row_data_processor(row):
        emit_game_order(row.user_id, PLATFORM_TYPE.METIS, row.game_id, row.ticket_id, row.bet_amount, row.bet_result,
                        row.create_time)

    batch_template(row_data_processor, MetisBetLogs)


# hera
# def sync_bet_hera():
#     def row_data_processor(row):
#         emit_game_order(row.user_id, PLATFORM_TYPE.HERA, row.game_id, row.ticket_id, row.bet_amount, row.bet_result,
#                         row.create_time)
#
#     batch_template(row_data_processor, HeraBetLogs)


def batch_template(row_data_processor, src_model):
    table_name = src_model.__table__.name
    last_cursor = ProxyAgent().get('bigbang:analysis:game:id:%s' % table_name)
    last_id = None
    if last_cursor:
        last_id = int(last_cursor)
    init_last_id = last_id
    batch_count = 0
    g_count = 0
    while True:
        _LOGGER.info('start sync [%s] since: [%s], the batch count: [%s]' % (table_name, last_id, batch_count))
        if last_id:
            query = src_model.query.filter(src_model.id > last_id).order_by(src_model.id.asc())
        else:
            query = src_model.query.order_by(src_model.id.asc())
        batch_data = query.limit(BATCH_COUNT).all()
        batch_count += 1
        if not batch_data:
            break
        for row in batch_data:
            row_data_processor(row)
            last_id = row.id
            g_count += 1

        ProxyAgent().set('bigbang:analysis:game:id:%s' % src_model.__table__.name, last_id)
    _LOGGER.info(
        'finished sync [%s], total count [%s] since [%s] to [%s]' % (table_name, g_count, init_last_id, last_id))
    orm.session.close()
